package com.cityguardian.threads;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.cityguardian.utils.Utils;
import com.cityguardian.ws.ConnectionThread;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;

public class AsyncTaskSubirFoto extends AsyncTask<Integer, Double, String>{

	private String path;
	private String idAlerta;
	
	public AsyncTaskSubirFoto(String path, String idAlerta){
		this.path=path;
		this.idAlerta=idAlerta;
		Log.d("path", path);
	}
	
	@Override
	protected String doInBackground(Integer... params) {
		
		String response = "0";
		response = subirFoto();
		
		return response;
	}

	private String subirFoto() {
		/*FileInputStream fileStream = null;
		
		try {
			fileStream = new FileInputStream(path);
	    } 
	    catch (FileNotFoundException e1) {
	        Log.e("FOTO", "Error cargando foto");
	        e1.printStackTrace();
	    } */
		
		//Bitmap bitmapOrg1 = BitmapFactory.decodeStream(fileStream);
		
		Bitmap bitmapOrg1 = Utils.decodeFile(path);
	    ByteArrayOutputStream bao1 = new ByteArrayOutputStream();
	    bitmapOrg1.compress(Bitmap.CompressFormat.JPEG, 90, bao1);
	    byte [] imagearray1 = bao1.toByteArray();
	    String ba1=Base64.encodeToString(imagearray1, Base64.DEFAULT);
	    
	    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
	    nameValuePairs.add(new BasicNameValuePair("image",ba1));
	    nameValuePairs.add(new BasicNameValuePair("idAlerta", idAlerta));
	    
	    try{
	        HttpClient httpclient = new DefaultHttpClient();
	        HttpPost httppost = new HttpPost(ConnectionThread.privateRoute+"/ws/foto/subirFoto");
	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	        HttpResponse response = httpclient.execute(httppost);
	        String entity = EntityUtils.toString(response.getEntity());
		    Log.e("FOTITO",entity.toString());
	        httpclient.getConnectionManager().shutdown(); 
	    }
	    catch(Exception e){
	        e.toString();
	        return "0";
	    }
	    
		return "1";
	}
		
}
